package com.chao.wind3j.base.config.shiroConfig.advisor;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
import org.apache.shiro.subject.Subject;

import java.lang.annotation.Annotation;

public class PermissionHandler extends AuthorizingAnnotationHandler  {
  public PermissionHandler() {
    super(CCPermissions.class);
  }

  @Override
  public void assertAuthorized(Annotation a) throws AuthorizationException {
    if (a instanceof CCPermissions) {
      CCPermissions annotation = (CCPermissions) a;
      String[] perms = annotation.value();
      Subject subject = getSubject();

      if (perms.length == 1) {
        subject.checkPermission(perms[0]);
        return;
      }
      // 多个权限，有一个就通过
      boolean hasAtLeastOnePermission = false;
      for (String permission : perms) {
        if (subject.isPermitted(permission)) {
          hasAtLeastOnePermission = true;
          break;
        }
      }
      // Cause the exception if none of the role match,
      // note that the exception message will be a bit misleading
      if (!hasAtLeastOnePermission) {
        subject.checkPermission(perms[0]);
      }
    }
  }

}
